package controller;

import dao.AdministratorDao;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/login")
public class Administrator {
    @Autowired
    private AdministratorDao admins;
    @RequestMapping("/exits")
    public String exits(@Validated @ModelAttribute("a") entity.Administrator admin, BindingResult bin, HttpServletRequest request){
        //Subject：即“当前操作用户”
        Subject subject = SecurityUtils.getSubject() ;
        //
        UsernamePasswordToken token = new UsernamePasswordToken(admin.getAname(),admin.getApwd()) ;
        //触发自定义real,如果没有注册自定义real,会报错
        //自定义real有两个方法
        //1.认证
        try {
            subject.login(token);

        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        if(bin.hasErrors()){
            return "redirect:/index.jsp";
        }else{
            entity.Administrator ad= admins.exits(admin);
            if(ad==null){
                return "redirect:/index.jsp";
            }else{
                request.getSession().setAttribute("Aid",ad.getAid());
                request.getSession().setAttribute("ad",ad);
                return "redirect:/role/PowerQuery";
            }

        }

    }
}
